package shovelsoft.btmetaparser;

import java.io.InputStream;
import java.util.LinkedList;
import shovelsoft.btmetaparser.tokens.Data;
import shovelsoft.btmetaparser.tokens.Dictionary;
import shovelsoft.btmetaparser.tokens.End;
import shovelsoft.btmetaparser.tokens.IToken;
import shovelsoft.btmetaparser.tokens.List;
import shovelsoft.btmetaparser.tokens.Integer;

/***
 * Tokenise the given binary encoded InputStream ( raw Bit-torrent meta-data )
 * @author cds
 */
public class Tokenise {
	
	public final java.util.List<IToken> Tokens;
	
	/***
	 * Tokenise the given binary encoded input stream ( raw Bit-torrent meta-data )
	 * @param is Input Stream
	 * @throws Exception
	 */
	public Tokenise(InputStream is) throws Exception {
		
		int b;
		
		LinkedList<IToken> list = new LinkedList<IToken>();
		
		while((b = is.read())!=-1)
			switch(b) {
				case 'd':
					list.add(Dictionary.getInstance());
					break;
				case 'l':
					list.add(List.getInstance());
					break;
				case 'e':
					list.add(End.getInstance());
					break;
				case 'i':
					list.add(new Integer(is));
					break;
				default:
					list.add(new Data(b, is));
					break;
			}
		Tokens = list;
	}
	
	@Override
	public String toString() {
		
		StringBuilder sb = new StringBuilder();
	
		int depth = 0;
		
		for(IToken tok : Tokens)
		{
			if(tok instanceof shovelsoft.btmetaparser.tokens.End)
				--depth;
			
			for(int i=0;i<=depth;++i)
				sb.append("* ");
			sb.append(tok + "\n");
			
			if(tok instanceof shovelsoft.btmetaparser.tokens.Dictionary)
				++depth;
			if(tok instanceof shovelsoft.btmetaparser.tokens.List)
				++depth;
		}
		
		return sb.toString();
	}
	
}

